<template>
  <div class="page-container">
    <div class="page-header" style="display: flex; align-items: center; justify-content: space-between;">
      <h1 class="page-title">用户管理</h1>
      <el-button type="primary" @click="showAddDialog" style="font-size: 20px; font-weight: bold; letter-spacing: 2px; text-transform: uppercase; height: 48px; min-width: 160px;">
        添加用户
      </el-button>
    </div>
    
    <el-card shadow="hover">
      <div class="filter-container">
        <el-input
          placeholder="搜索用户名"
          v-model="searchQuery"
          style="width: 300px;"
          clearable
          @keyup.enter.native="handleSearch"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
        </el-input>
        
        <el-select v-model="roleFilter" placeholder="用户角色" clearable style="width: 120px; margin-left: 10px; text-transform: uppercase; font-size: 16px;" @change="handleRoleFilterChange">
          <el-option label="管理员" value="admin"></el-option>
          <el-option label="普通用户" value="user"></el-option>
        </el-select>
      </div>
      
      <el-table
        :data="users"
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="60"></el-table-column>
        <el-table-column prop="username" label="用户名" width="120"></el-table-column>
        <el-table-column prop="age" label="年龄" width="80"></el-table-column>
        <el-table-column prop="gender" label="性别" width="80"></el-table-column>
        <el-table-column prop="ethnicity" label="民族" width="100"></el-table-column>
        <el-table-column prop="mandarin_level" label="普通话水平" width="120"></el-table-column>
        <el-table-column label="角色" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.role === 'admin' ? 'danger' : 'success'">
              {{ scope.row.role === 'admin' ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="录音数量" width="100">
          <template slot-scope="scope">
            {{ scope.row.recording_count || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.row)"
              plain
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
              plain
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        >
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 添加/编辑用户对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" :title-style="{fontSize: '26px', fontWeight: 'bold'}">
      <el-form :model="userForm" :rules="userRules" ref="userForm" label-width="120px" style="font-size: 20px;">
        <el-form-item label="用户名" prop="username" style="font-size: 20px;">
          <el-input v-model="userForm.username" :disabled="isEdit" style="font-size: 20px;"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit" style="font-size: 20px;">
          <el-input v-model="userForm.password" type="password" style="font-size: 20px;"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role" style="font-size: 20px;">
          <el-select v-model="userForm.role" placeholder="请选择角色" style="width: 100%; font-size: 20px;" @change="handleRoleChange">
            <el-option label="管理员" value="admin"></el-option>
            <el-option label="普通用户" value="user"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age" v-if="userForm.role === 'user'" style="font-size: 20px;">
          <el-input-number v-model="userForm.age" :min="1" :max="120" style="width: 100%; font-size: 20px;"></el-input-number>
        </el-form-item>
        <el-form-item label="性别" prop="gender" v-if="userForm.role === 'user'" style="font-size: 20px;">
          <el-select v-model="userForm.gender" placeholder="请选择性别" style="width: 100%; font-size: 20px;">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="民族" prop="ethnicity" v-if="userForm.role === 'user'" style="font-size: 20px;">
          <el-select v-model="userForm.ethnicity" placeholder="请选择民族" style="width: 100%; font-size: 20px;">
            <el-option label="汉族" value="汉族"></el-option>
            <el-option label="壮族" value="壮族"></el-option>
            <el-option label="满族" value="满族"></el-option>
            <el-option label="回族" value="回族"></el-option>
            <el-option label="苗族" value="苗族"></el-option>
            <el-option label="维吾尔族" value="维吾尔族"></el-option>
            <el-option label="土家族" value="土家族"></el-option>
            <el-option label="彝族" value="彝族"></el-option>
            <el-option label="蒙古族" value="蒙古族"></el-option>
            <el-option label="藏族" value="藏族"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="普通话水平" prop="mandarin_level" v-if="userForm.role === 'user'" style="font-size: 20px;">
          <el-select v-model="userForm.mandarin_level" placeholder="请选择普通话水平" style="width: 100%; font-size: 20px;">
            <el-option label="一级甲等" value="一级甲等"></el-option>
            <el-option label="一级乙等" value="一级乙等"></el-option>
            <el-option label="二级甲等" value="二级甲等"></el-option>
            <el-option label="二级乙等" value="二级乙等"></el-option>
            <el-option label="三级甲等" value="三级甲等"></el-option>
            <el-option label="三级乙等" value="三级乙等"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" style="font-size: 20px; min-width: 120px;">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading" style="font-size: 20px; min-width: 120px;">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Users',
  data() {
    return {
      users: [],
      loading: false,
      submitLoading: false,
      searchQuery: '',
      roleFilter: '',
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      dialogTitle: '添加用户',
      userForm: {
        id: null,
        username: '',
        age: 18,
        gender: '男',
        ethnicity: '',
        mandarin_level: '',
        password: '',
        role: 'user'
      },
      userRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在3到20个字符之间', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'change' },
          { type: 'number', message: '年龄必须为数字', trigger: 'change' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        ethnicity: [
          { required: true, message: '请输入民族', trigger: 'blur' }
        ],
        mandarin_level: [
          { required: true, message: '请选择普通话水平', trigger: 'change' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度至少6个字符', trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      },
      isEdit: false
    }
  },
  created() {
    this.fetchUsers()
  },
  methods: {
    async fetchUsers() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.currentPage,
          limit: this.pagination.pageSize,
          search: this.searchQuery,
          role: this.roleFilter
        }
        
        const result = await this.$store.dispatch('fetchUsers', params)
        console.log('Users组件接收到的数据:', result)
        
        // 检查数据结构并适配
        let usersList = [];
        if (result && Array.isArray(result.items)) {
          usersList = result.items;
          this.pagination.total = result.total;
        } else if (result && Array.isArray(result.users)) {
          // 适配API文档中描述的数据结构
          usersList = result.users;
          this.pagination.total = result.total;
        } else if (Array.isArray(result)) {
          // 如果直接返回数组
          usersList = result;
          this.pagination.total = result.length;
        } else {
          console.error('未知的数据结构:', result);
          usersList = [];
          this.pagination.total = 0;
        }
        
        // 获取每个用户的录音数量
        for (const user of usersList) {
          try {
            const count = await this.$store.dispatch('fetchUserRecordingCount', user.id);
            user.recording_count = count;
          } catch (error) {
            console.error(`获取用户 ${user.id} 的录音数量失败:`, error);
            user.recording_count = 0;
          }
        }
        
        this.users = usersList;
      } catch (error) {
        console.error('获取用户列表失败:', error)
        this.$errorMessage('获取用户列表失败')
      } finally {
        this.loading = false
      }
    },
    
    handleSearch() {
      this.pagination.currentPage = 1
      this.fetchUsers()
    },
    
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchUsers()
    },
    
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.fetchUsers()
    },
    
    showAddDialog() {
      this.isEdit = false
      this.dialogTitle = '添加用户'
      this.userForm = {
        id: null,
        username: '',
        age: 18,
        gender: '男',
        ethnicity: '',
        mandarin_level: '',
        password: '',
        role: 'user'
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.userForm && this.$refs.userForm.clearValidate()
      })
    },
    
    handleEdit(row) {
      this.isEdit = true
      this.dialogTitle = '编辑用户'
      this.userForm = {
        id: row.id,
        username: row.username,
        age: row.age || 18,
        gender: row.gender || '男',
        ethnicity: row.ethnicity || '',
        mandarin_level: row.mandarin_level || '',
        role: row.role || 'user'
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.userForm && this.$refs.userForm.clearValidate()
      })
    },
    
    async handleDelete(row) {
      // 不允许删除自己
      if (row.id === this.$store.getters.user.id) {
        this.$errorMessage('不能删除当前登录的用户')
        return
      }
      
      try {
        await this.$confirm('此操作将永久删除该用户，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        this.loading = true
        await this.$store.dispatch('deleteUser', row.id)
        this.$successMessage('删除成功')
        this.fetchUsers()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除用户失败:', error)
          this.$errorMessage('删除用户失败')
        }
      } finally {
        this.loading = false
      }
    },
    
    submitForm() {
      this.$refs.userForm.validate(async valid => {
        if (valid) {
          this.submitLoading = true
          try {
            if (this.isEdit) {
              const userData = {
                age: this.userForm.age,
                gender: this.userForm.gender,
                ethnicity: this.userForm.ethnicity,
                mandarin_level: this.userForm.mandarin_level,
                role: this.userForm.role
              }
              
              await this.$store.dispatch('updateUser', {
                id: this.userForm.id,
                userData
              })
              this.$successMessage('更新成功')
            } else {
              // 管理员时补全默认字段，避免后端报错
              let submitData = { ...this.userForm }
              if (submitData.role === 'admin') {
                submitData.age = 18
                submitData.gender = '男'
                submitData.ethnicity = '汉族'
                submitData.mandarin_level = '一级甲等'
              }
              await this.$store.dispatch('addUser', submitData)
              this.$successMessage('添加成功')
            }
            this.dialogVisible = false
            this.fetchUsers()
          } catch (error) {
            console.error('操作失败:', error)
            this.$errorMessage(this.isEdit ? '更新失败' : '添加失败')
          } finally {
            this.submitLoading = false
          }
        }
      })
    },
    handleRoleChange() {
      // 切换角色时重置普通用户专属字段
      if (this.userForm.role === 'admin') {
        this.userForm.age = 18;
        this.userForm.gender = '男';
        this.userForm.ethnicity = '';
        this.userForm.mandarin_level = '';
      }
    },
    handleRoleFilterChange() {
      this.pagination.currentPage = 1
      this.fetchUsers()
    },
  }
}
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
  display: flex;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 